(function() {

    var
    $u = juliet.using({
        validationEvent : 'juliet.validation.validationEvent-0.2',
        Observer : 'juliet.core.Observer-0.1'
    }),
    ve = $u('validationEvent'),
    $ = juliet.jQuery;

    var InputHelperClass = function() {

        this.selector = null;

        this.currentValue = null;

        this.previousValue = null;

        this.focusValue = null;

        this.observer = juliet.createObject($u('Observer'));

        this.getInputValue = function() {
            var result = [];

            $(this.selector).each(function() {
                var inputType = this.type;

                if (inputType == 'checkbox') {
                    result.push(this.checked);
                } else if (inputType == 'radio') {
                    if (this.checked) result.push(this.value);
                } else {
                    result.push(this.value);
                }
            });

            return ((result.length == 1) ? result[0] : result);
        };

        this.onInputEventHandler = function(eventType) {
            var
            inputValue = this.getInputValue(),
            event = ve.parse(eventType);

            if ((event == ve.KEY_UP) && this.isValuesEquals(inputValue, this.currentValue)) {
                return;
            }

            this.previousValue = this.currentValue;
            this.currentValue = inputValue;

            if (event == ve.FOCUS) {
                this.focusValue = this.currentValue;
            } else if ((event == ve.BLUR) && !this.isValuesEquals(this.focusValue, this.currentValue)) {
                event = ve.CHANGE;
            }

            this.observer.notify('input-event', event);
        };

        this.bindInputEventHandler = function() {
            var self = this;

            $(this.selector).each(function() {
                var inputType = this.type, bindEvents;

                if ((inputType == 'checkbox') || (inputType == 'radio') || (inputType == 'file')) bindEvents = 'change';
                else bindEvents = 'keyup focus blur';

                $(this).bind(bindEvents, function(e) {
                    self.onInputEventHandler(e.type);
                });
            });
        };

        this.isValuesEquals = function(value1, value2) {
            if ((value1 instanceof Array) && (value2 instanceof Array)) {
                return value1.toString() === value2.toString();
            }

            return (value1 === value2);
        };

        this.initialize = function(fieldSelector) {
            this.selector = fieldSelector;
            this.bindInputEventHandler();
            this.onInputEventHandler('focus');
        };

    };

    juliet.registerModule('juliet.validation', 'InputHelper-0.2', InputHelperClass);

})();
